﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Freight.Redis.Net;
using Newtonsoft.Json;
using StackExchange.Redis;
using Stock.Client.Utils;
using Stock.Model.WX;

namespace Stock.Client.Service
{
      public class RedisService
      {
            private static void SetCon()
            {
                  if (!RedisHelper.HasCon())
                        RedisHelper.SetCon(ConfigurationManager.AppSettings["Redis"].ToString());
            }

            public static void SetValue(string key, string value, int expireMinutes = 0)
            {
                  SetCon();
                  RedisHelper.SetString(key, value, expireMinutes);
                  RedisHelper.Close();
            }

            public static string GetValue(string key)
            {
                  SetCon();
                  string value = RedisHelper.GetString(key).ToString();
                  RedisHelper.Close();
                  return value;
            }

            public static Token GetToken()
            {
                  //先从REDIS中查找
                  SetCon();
                  string a = RedisHelper.GetString("WXToken");
                  Token token = null;
                  if (string.IsNullOrEmpty(a))
                  {
                         
                  }
                  else
                        token = JsonConvert.DeserializeObject<Token>(a);
                  if (token == null)
                  {
                        string url = string.Format(ConfigurationManager.AppSettings["WXToken"].ToString(),
                              ConfigurationManager.AppSettings["AppID"], ConfigurationManager.AppSettings["AppSecret"]);
                        token = JsonConvert.DeserializeObject<Token>(HttpUtils.GetSendAsync(url).Result);
                        RedisHelper.SetString("WXToken", JsonConvert.SerializeObject(token), token.expires_in / 60, When.Always, CommandFlags.None);                      
                        //RedisHelper.HashSet("WX", "TOKEN", JsonConvert.SerializeObject(token), When.Always,CommandFlags.None);
                  }
                  return token;
            }
      }
}
